﻿using System.IO;
using System.Text;
using System.Xml.Serialization;
using System.Runtime.Serialization.Json;

namespace WebConversion.Common
{
    public static class Utility
    {
        public static T DeserializeXml<T>(string xmlString)
        {
            using (var rdr = new StringReader(xmlString))
            {
                var serializer = new XmlSerializer(typeof(T));
                return (T)serializer.Deserialize(rdr);
            }
        }

        public static string JsonSerializer<T>(T t)
        {
            var jsonSerializer = new DataContractJsonSerializer(typeof(T));

            using (var memoryStream = new MemoryStream())
            {
                jsonSerializer.WriteObject(memoryStream, t);
                return Encoding.UTF8.GetString(memoryStream.ToArray());
            }
        }

        public static T JsonDeserialize<T>(string jsonString)
        {
            var jsonSerializer = new DataContractJsonSerializer(typeof(T));
            var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
            return (T)jsonSerializer.ReadObject(memoryStream);
        }
    }
}
